package evaluation;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;

import modex.Paragraphe;

import bddaccess.DAOFactory;
import bddaccess.DocumentDAO;
import bddaccess.ParagrapheDAO;

public class ParserQrels {

	public ArrayList<Paragraphe> parseQrels(int numRequest){
		ArrayList<Paragraphe> resultList = new ArrayList<Paragraphe>();
		String[] splittedQrel = null;
		String fichier="";
		ParagrapheDAO paraDAO = DAOFactory.getParagrapheDAO();
		DocumentDAO docDAO = DAOFactory.getDocumentDAO();
		
		if (numRequest < 10){
			fichier ="./resources/Qrels/qrel0"+numRequest+".txt";			
		} else {
			fichier ="./resources/Qrels/qrel"+numRequest+".txt";	
		}
		
		System.out.println("Parsing " + fichier + " ...");
		
		try{
			InputStream ips=new FileInputStream(fichier); 
			InputStreamReader ipsr=new InputStreamReader(ips);
			BufferedReader br=new BufferedReader(ipsr);
			String line;
			while ((line=br.readLine())!=null){
				// Parse the different things and create the Qrel object
				splittedQrel = line.split(" |\t", -1);
				
				// Si la Qrel est pertinente
				if (Integer.parseInt(splittedQrel[2]) == 1){
					
					// On enlève la chaine de caractères "Collection/"
					String arg0 = splittedQrel[0];
					String nomDocument = arg0.substring(arg0.indexOf("d"), arg0.indexOf(".xml"));
					
					// On créé l'objet Qrel et on le rajoute à la liste
					//qrel = new Qrel(nomDocument, splittedQrel[1], Integer.parseInt(splittedQrel[2]));
					
					Paragraphe p = paraDAO.findByXpathAndDocId(splittedQrel[1], docDAO.getIdDocByName(nomDocument));
					
					//qrel = new Qrel(p, Integer.parseInt(splittedQrel[2]));
					resultList.add(p);
				}
			}
			br.close(); 
		}		
		catch (Exception e){
			System.out.println(e.toString());
		}

		System.out.println("Fin parsing ...");
		return resultList;		
	}
	
}
